package coms.action;

import Util.XMLUtil;
import coms.delegates.ReviewDelegate;
import coms.delegates.UserDelegate;
import coms.dto.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.struts2.ServletActionContext;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.XMLOutputter;

public class ReviewAction extends ComsActionSupport {

    ReviewDelegate reviewDelegate;
    private List<Review> reviewList;
    private Review review;
    private List<Section> sectionList;
    private String action;
    private int reviewId;
    private String commentToAuthor;
    private String commentToAdmin;
    private boolean admin;

    public boolean isAdmin() {
         User u = (User) getSession().get("user");
        if (u != null) {
            admin = u.isAdmin();
        } 
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    public ReviewAction() {
        review = new Review();
        sectionList = new ArrayList<Section>();
        reviewList = new ArrayList<Review>();
        reviewDelegate = new ReviewDelegate();
    }

    public void assignSession() {
        Map<String, Object> sessionMap = getSession();
        User u = (User) sessionMap.get("user");
        if (u != null) {
            admin = u.isAdmin();
        }

    }

    public String search() {
        assignSession();
        
          User user = (User) session.get("user"); 
          if (user == null) { 
              return "login"; 
          }
        
        try {
         //   reviewList = reviewDelegate.findAll();
              reviewList = reviewDelegate.findByReviewer(user);
            System.out.println("review size" + reviewList.size());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "search";

    }

    public String input() {
        assignSession();
        populateReview();

        try {
            User user = (User) session.get("user");
            System.out.println("");
            /*
             * if (user == null) { return "login"; }
             *
             */

            String path = ServletActionContext.getServletContext().getRealPath("xml/review.xml");
            sectionList = XMLUtil.getReviewSectionListFromFile(path);
            session.put("sections", sectionList);

        } catch (Exception e) {
            e.printStackTrace();

        }


        return ComsActionSupport.INPUT;
    }

    public String view() {
        assignSession();
        populateReview();

        System.out.println("######## review id  = " + review.getId());
        System.out.println("######## comment to author  = " + review.getCommentToAuthor());
        System.out.println("######## comment to admin  = " + review.getCommentToAdministrator());
        String reviewXML = review.getReviewXML();
        Document reviewXMLDoc = XMLUtil.parseStrToDocument(reviewXML);
        sectionList = XMLUtil.getReviewSectionList(reviewXMLDoc);
        for (Section s : sectionList) {
            for (Heading h : s.getHeadings()) {

                for (Rating r : s.getRatings()) {
                    if (h.getRating() == Integer.parseInt(r.getValue())) {
                        h.setRateValue(r.getCaption());
                        break;
                    }
                }
            }


        }
        return "view";
    }

    public String submit() {
        assignSession();
        System.out.println("######## review id  = " + review.getId());
        System.out.println("######## comment to author  = " + review.getCommentToAuthor());
        System.out.println("######## comment to admin  = " + review.getCommentToAdministrator());
        /*
         *
         * if (session.get("review") == null) { return "error"; }
         *
         */
        //  review = (Review) session.get("review");


        if (session.get("review") == null) {
            return "error";
        }
        
       
       review = (Review) session.get("review");

         populateReview();
         review.setCommentToAdministrator(commentToAdmin);
         review.setCommentToAuthor(commentToAuthor);

        String path = ServletActionContext.getServletContext().getRealPath("xml/review.xml");
        User user = (User) session.get("user");
        /*
         * if (user == null) { return "login"; }
         */
        try {
            Document document = XMLUtil.parseXMLToDocument(path);
            Element root = document.getRootElement();
            List sectionElms = root.getChildren("section");

            for (int i = 0; i < sectionElms.size(); i++) {

                Element node = (Element) sectionElms.get(i);

                // Headings
                List headings = node.getChild("headings").getChildren();
                //  List<Heading> headingList = new ArrayList<Heading>();
                for (int j = 0; j < headings.size(); j++) {

                    Element heading = (Element) headings.get(j);
                    String idStr = (String) heading.getAttributeValue("id");
                    String ratingStr = request.getParameter(idStr);
                    System.out.println("rating" + ratingStr);
                    int rating = 0;
                    if (ratingStr == null || ratingStr.equals("")) {
                        rating = -1;
                    } else {
                        rating = new Integer(ratingStr).intValue();
                    }
                    heading.setAttribute("rating", rating + "");
                }
            }

            XMLOutputter xmOut = new XMLOutputter();
            String reviewXML = xmOut.outputString(document);
            System.out.println("----" + reviewXML);
            review.setReviewXML(reviewXML);
            review.setDateReviewed(new Date());
            //review.setReviewer(user);
            // review.setCommentToAdministrator(action);
            reviewDelegate.submitReview(review);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ComsActionSupport.SUCCESS;
    }

    public Review getReview() {
        return review;
    }

    public void setReview(Review review) {
        this.review = review;
    }

    public List<Review> getReviewList() {
        return reviewList;
    }

    public void setReviewList(List<Review> reviewList) {
        this.reviewList = reviewList;
    }

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    public List<Section> getSectionList() {
        return sectionList;
    }

    public void setSectionList(List<Section> sectionList) {
        this.sectionList = sectionList;
    }

    
    public void setReviewId(String reviewIdStr) {

        if (reviewIdStr != null && !reviewIdStr.equals("")) {
            reviewId = Integer.parseInt(reviewIdStr);
            review.setId(reviewId);
        }

       populateReview();

      session.put("review", review);


    }

    private void populateReview() {
        try {
            System.out.println("Review Id:" + reviewId + "");
            review = reviewDelegate.getById(reviewId);
        } catch (Exception ex) {
            Logger.getLogger(ReviewAction.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public String getCommentToAdmin() {
        return review != null ? review.getCommentToAdministrator() : commentToAdmin;
    }

    public void setCommentToAdmin(String commentToAdmin) {
        this.commentToAdmin = commentToAdmin;
        if (review != null) {
            review.setCommentToAdministrator(commentToAdmin);
        }
    }

    public String getCommentToAuthor() {
        return review != null ? review.getCommentToAuthor() : commentToAuthor;
    }

    public void setCommentToAuthor(String commentToAuthor) {
        this.commentToAuthor = commentToAuthor;
        if (review != null) {
            review.setCommentToAuthor(commentToAuthor);
        }
    }
}
